package com.okilo.online.app.fmt

import android.Manifest
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.okilo.online.app.R
import com.okilo.online.app.act.OkiloApplyAct
import com.okilo.online.app.act.OkiloPermAct
import com.okilo.online.app.act.OkiloProcessStepsAct
import com.okilo.online.app.common.OkiloComFmt
import com.okilo.online.app.databinding.OkiloFmtHomeBinding
import com.okilo.online.app.dialog.OkiloHomeLimitIncreasedDlog
import com.okilo.online.app.event.OkiloEventData
import com.okilo.online.app.event.OkiloEventPointType
import com.okilo.online.app.event.room.OkiloPointManager
import com.okilo.online.app.pet.OkiloLoanPet
import com.okilo.online.app.pet.view.IOkiloLoan
import com.okilo.online.app.tools.apt.OkiloOnSingleClickListener
import com.okilo.online.app.tools.extensions.addCommasFromEndRegex
import com.okilo.online.app.tools.helper.OkiloConfigProcessHp
import com.okilo.online.app.tools.log.OkiloLog
import com.okilo.online.app.tools.shared.OkiloSharedHp
import com.okilo.online.app.tools.shared.OkiloSharedKey
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import java.math.BigDecimal

/**
 * OkiloLoan
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：首页 额度
 */
class OkiloHomeLimitFmt : OkiloComFmt(), IOkiloLoan.IOkiloHomeLimit, IOkiloLoan.IOkiloRepay {
    private var _binding: OkiloFmtHomeBinding? = null
    private var okiloLimitPet: OkiloLoanPet? = null

    private var scaleAnimator: ValueAnimator? = null

    override val pageName: String = "Home_Page"

    override fun createOkiloContentView(inflater: LayoutInflater): View? {
        _binding = OkiloFmtHomeBinding.inflate(layoutInflater)
        return _binding?.root
    }

    override fun initializeOkiloViews() {
        _binding?.okiloHomeRefreshLayout?.setColorSchemeResources(R.color.okilo_color_theme, R.color.okilo_color_black)
        startBounceAnimation(_binding?.okiloHomeButtonApply)
    }

    override fun setupOkiloEventListeners() {
        _binding?.okiloHomeRefreshLayout?.setOnRefreshListener {
            publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_PROCESS_REFRESH))
        }
        _binding?.okiloHomeButtonApply?.setOnClickListener(object : OkiloOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                //待还款
                val isRepay = OkiloConfigProcessHp.iOkiloApplyOrderRepay()
                if (isRepay){
                    //显示待还款
                    addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.HOME_REPAY_NOW,pageName)
                    publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_SHOW_REPAY))
                } else {
                    addEventPointRequestAction(OkiloEventPointType.OKILO_CLICK_TRACK.HOME_APPLY_NOW,pageName)
                    checkOkiloPermissions()
                }
                // TODO: 首页点申请 需上报所有埋点
                OkiloPointManager.getInstance().manualReport()
            }
        })
    }

    override fun loadOkiloData() {
        if (okiloLimitPet == null){
            okiloLimitPet = OkiloLoanPet(this)
        }
        //首次加载如果是待还款，直接进入待还款tab
        val isRepay = OkiloConfigProcessHp.iOkiloApplyOrderRepay()
        if (isRepay){
            //待还款
            _binding?.okiloHomeButtonApply?.callOnClick()
        }
        onOkiloHomeLimitRefreshData()
    }

    /**
     * 刷新数据
     */
    fun onOkiloHomeLimitRefreshData(){
        //待还款
        val isRepay = OkiloConfigProcessHp.iOkiloApplyOrderRepay()
        if (isRepay){
            //待还款 - 获取还款信息
//            okiloLimitPet?.gOkiloRepayInfoRequest(this)
            return
        }
        //获取首页额度信息
        okiloLimitPet?.gOkiloHomeLimitRequest(this)
    }

    private fun startBounceAnimation(view: View?) {
        if (view == null){
            return
        }
        scaleAnimator = ValueAnimator.ofFloat(1.0f, 0.7f, 1.0f).apply {
            duration = 1500 // 动画时长 1秒
            repeatCount = ValueAnimator.INFINITE // 无限循环
            repeatMode = ValueAnimator.RESTART // 循环模式：重新开始
            addUpdateListener { animation ->
                val scale = animation.animatedValue as Float
                view.scaleX = scale
                view.scaleY = scale
            }
            start()
        }
    }

    /**
     * 显示额度
     */
    override fun sOkiloHomeLimitCallback(obj: JSONObject) {
        val binding = _binding ?: return
        binding.okiloHomeAmountType.text =  getString(R.string.okilo_home_max_loan_amount)
        binding.okiloHomeTextApply.text = getString(R.string.okilo_home_apply_now)
        binding.okiloHomeAmount.text = BigDecimal(obj.optString("amount")).stripTrailingZeros().toPlainString().addCommasFromEndRegex()
    }

    /**
     * 显示待还款信息
     */
    override fun sOkiloLoadRepayInfo(data: JSONObject) {
        val binding = _binding ?: return
        binding.okiloHomeAmountType.text =  getString(R.string.okilo_home_total_repayment)
        binding.okiloHomeTextApply.text = getString(R.string.okilo_home_repay_now)
        binding.okiloHomeAmount.text = BigDecimal(data.optString("repayAmount")).stripTrailingZeros().toPlainString().addCommasFromEndRegex()
    }

    /**
     * 额度增加提示
     */
    override fun sOkiloHomeLimitIncreasedCallback(data: JSONObject) {
        val dialog = OkiloHomeLimitIncreasedDlog(
            requireContext(),
            data.optString("product"),
            object : OkiloHomeLimitIncreasedDlog.IDialogCallback {
                override fun onClick(view: View?) {
                    //申请
                    _binding?.okiloHomeButtonApply?.callOnClick()
                }
            })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        dialog.sOkiloHomeLimitIncreasedDlogData(data)
    }

    /**
     * 请求完成
     */
    override fun sOkiloHomeRequestFinish() {
        hideOkiloLoading()
    }

    /**
     * 权限声明列表
     */
    private val permissionResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                //权限页操作状态 : 0未操作  1已同意  -1拒绝
                val permissionStatus = OkiloSharedHp.gOkiloSharedInt(OkiloSharedKey.SP_OKILO_PERMISSIONS_STATUS)
                //权限列表未操作，直接点击系统返回
                if (permissionStatus == 0){
                    return@registerForActivityResult
                }
                var isNext = false
                result.data?.let { bundle ->
                    val isAgree = bundle.getBooleanExtra("isGranted",false)
                    OkiloLog.i(">>>>>>>>>permission is agree ：$isAgree")
                    //同意，校验权限 进行下一步
                    isNext = if (isAgree){
                        true
                    } else {//拒绝，
                        //是否是广告渠道
                        val isAdSource = OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_IS_ADSOURCE)
                        //非广告渠道才继续校验进行下一步
                        !isAdSource
                    }
                }
                if (isNext){
                    checkOkiloPermissions()
                }
            }
        }
    }

    /**
     * 检查权限
     */
    private fun checkOkiloPermissions(){
        //权限页操作状态 : 0未操作  1已同意  -1拒绝
        val permissionStatus = OkiloSharedHp.gOkiloSharedInt(OkiloSharedKey.SP_OKILO_PERMISSIONS_STATUS)
        //权限列表未操作 -> 进入权限列表
        if (permissionStatus == 0){
            pushOkiloPermissionsPage()
            return
        }
        //是否是广告渠道
        val isAdSource = OkiloSharedHp.gOkiloSharedBoolean(OkiloSharedKey.SP_OKILO_IS_ADSOURCE)
        //广告渠道 && 权限列表未同意 -> 进入权限列表
        if (isAdSource && permissionStatus == -1){
            pushOkiloPermissionsPage()
            return
        }
        //广告渠道 && 未同意sms权限 -> 进入权限列表
        if (isAdSource && !EasyPermissions.hasPermissions(requireContext(), Manifest.permission.READ_SMS)){
            pushOkiloPermissionsPage()
            return
        }

        //已同意权限列表 && 已同意SMS权限 -> 上报设备数据
        if (permissionStatus == 1 && EasyPermissions.hasPermissions(requireContext(), Manifest.permission.READ_SMS)){
            //上报所有设备数据
            publishEventData(OkiloEventData(OkiloEventData.TYPE.OKILO_SYC_ALL_DEVICE))
        }

        // 进件信息未完成
        if (OkiloConfigProcessHp.gOkiloConfigProcessStepList().isNotEmpty()){
            pushOkiloProcessStepsPage()
            return
        }

        //权限已全部同意 && 进件信息已完成 - 申贷试算页面
        pushOkiloApplyPage()
    }

    /**
     * 进入权限列表页面
     */
    private fun pushOkiloPermissionsPage(){
        val intent = Intent(context, OkiloPermAct::class.java)
        permissionResultLauncher.launch(intent)
    }

    /**
     * 进入填写进件信息页面
     */
    private fun pushOkiloProcessStepsPage(){
        OkiloProcessStepsAct.Companion.start(requireContext())
    }

    /**
     * 进入申贷页面
     */
    private fun pushOkiloApplyPage(){
        OkiloApplyAct.Companion.start(requireContext())
    }

    override fun onOkiloPublishEvent(event: OkiloEventData) {
        super.onOkiloPublishEvent(event)
        when (event.eventType) {
            OkiloEventData.TYPE.OKILO_DATA_REFRESH,
            OkiloEventData.TYPE.OKILO_PROCESS_REFRESHED -> { //刷新流程完成
            }

            OkiloEventData.TYPE.OKILO_REPAY_INFO_REFRESHED -> {//待还款数据刷新完成
                hideOkiloLoading()
                val data = event.eventData
                sOkiloLoadRepayInfo(data)
            }

            OkiloEventData.TYPE.OKILO_SHOW_AUTHENTICATION -> {
            }
            OkiloEventData.TYPE.OKILO_HTTP_REQUEST_ERROR -> {
                hideOkiloLoading()
            }
            else -> {

            }
        }
    }

    override fun hideOkiloLoading() {
        super.hideOkiloLoading()
        _binding?.okiloHomeRefreshLayout?.isRefreshing = false
    }

    override fun onPause() {
        super.onPause()
        scaleAnimator?.pause()
    }

    override fun onResume() {
        super.onResume()
        scaleAnimator?.resume()
    }

    override fun onDestroyView() {
        scaleAnimator?.let {
            it.cancel()
            it.removeAllUpdateListeners() // 移除监听器，避免持有 View 引用
        }
        scaleAnimator = null
        super.onDestroyView()
        hideOkiloLoading()
        _binding = null
    }
}